package test.redis.tool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.log4j.Logger;

/**
 * 
 * @Description 序列化对象 和反序列化对象
 * @author HZdaiyuan
 * @Date 2015-7-20 下午7:30:37
 * @version
 * 
 */
public class SerializeUtil {
    private static final Logger logger = Logger.getLogger(SerializeUtil.class);

    public static byte[] serialize(Object object) {
        if (!(object instanceof Serializable)) {
            System.err.print("can't serialize,cause by not serializable subclass");
            return null;
        }

        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (IOException e) {
            logger.error("serialize error", e);
        } finally {
            try {
                oos.close();// 会调用内层io,close;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        if (null == bytes || bytes.length == 0) {
            return null;
        }

        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (ClassNotFoundException e) {
            logger.error("classNotFound error", e);
        } catch (IOException e) {
            logger.error("IO error", e);
        } finally {
            try {
                if (null != ois) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
